#include "../include/kc.h"
#include "../include/defs.h"
#include "../include/shmem.h"

SHARED zonas[MAXZONAS];

int inicializaShmem = 0;

void
iniciarShmem (void) {
    int i;

    for (i = 0; i < MAXZONAS; i++) {
        zonas[i].key = -1;
        zonas[i].locked = 0;
    }

    inicializaShmem = 1;
}

int
shmget(int key, int size) {
    int id;

    if (!inicializaShmem)
        iniciarShmem ();

    if (key < 0 || size <= 0)
        return -1;

    id = getKeyId (key);
    if (id == -1) {
        id = addNewKey (key, size);
    }

    return id;
}

void *
shmat(int id) {
    if (id < 0 || id >= MAXZONAS)
        return (void *) 0x0;

    // si no tiene key asociada me mandaron frula
    if (zonas[id].key == -1)
        return (void *) 0x0;
    else
        return (void *) zonas[id].addr;
}

int
getKeyId(int key) {
    int i;

    for (i = 0; i < MAXZONAS; i++) {
        if (zonas[i].key == key)
            return i;
    }

    return -1;
}

int
addNewKey(int key, int size) {
    int i;

    for (i = 0; i < MAXZONAS; i++) {
        // busco la primera que este libre (key = -1)
        if (zonas[i].key == -1) {
            zonas[i].key = key;
            zonas[i].size = size;
            zonas[i].addr = (int) getSharedBlock (size);
            zonas[i].locked = 0;
            return i;
        }
    }
    return -1;
}

int
lockMyMem(int id) {
    if (id < 0 || id >= MAXZONAS)
        return -1;

    if (zonas[id].locked)
        return -1;
    else {
        zonas[id].locked = 1;
        return 1;
    }
}

int
unlockMyMem(int id) {
    if (id < 0 || id >= MAXZONAS)
        return -1;

    zonas[id].locked = 0;
    return 1;
}
